package com.db.controller;

import com.db.entity.User;
import com.db.service.UserService;
import com.db.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");


        HttpSession session = request.getSession(true);
        Object obj = session.getAttribute("login");

        if(obj != null){
            response.sendRedirect(request.getContextPath()+"/showPersons");
            return;
        }

        UserService us = new UserServiceImpl();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captchaCode = request.getParameter("captchaCode");

        User user1 = us.login(new User(null,username,password));

        String captcha = (String)session.getAttribute("captchaCode");
        System.out.println(captcha);

        if(user1 != null && captchaCode.equalsIgnoreCase(captcha)){

            /*Cookie cookie = new Cookie("login",username);
            response.addCookie(cookie);*/
            session.setAttribute("login",user1.getUsername());
            session.setAttribute("userid",user1.getId());
            String sessionid = session.getId(); //获取sessionid
            Cookie cookie = new Cookie("JSESSIONID", sessionid); //new一个cookie，cookie的名字是JSESSIONID跟带id的cookie一样
            cookie.setPath(request.getContextPath()); //设置cookie应用范围。getContextPath是获取当前项目的名字。
            //cookie.setMaxAge(60000); //设置有效时间
            response.addCookie(cookie);//用这个cookie把带id的cookie覆盖掉


            response.sendRedirect(request.getContextPath()+"/showPersons");
        }else{
            response.sendRedirect(request.getContextPath()+"/login.jsp");

        }

    }
}
